package com.lhj.security.service.impl;

import com.lhj.security.config.security.AuthenticationContextHolder;
import com.lhj.security.config.security.UserAuthDetail;
import com.lhj.security.config.security.service.TokenService;
import com.lhj.security.exception.PasswordMismatchException;
import com.lhj.security.service.ILoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author lhj
 * @Date 2024/12/27 10:16
 */
@Slf4j
@Service
public class LogicServiceImpl implements ILoginService {
    
    @Resource
    private AuthenticationManager authenticationManager;
    
    @Resource
    private TokenService tokenService;

    @Override
    public String doLogin(String username, String password) {
        Authentication authenticate = null;
        try {
            log.info("用户登陆开始 username:{}", username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContextHolder(authenticationToken);
            //这段代码会去调用UserDetailServiceImpl.loadUserByUsername()
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            log.error("用户登陆-异常, username:{}", username);
            if (e instanceof PasswordMismatchException) {
                log.error("用户登陆-密码错误 username:{}", username);
            }
            if (e instanceof UsernameNotFoundException) {
                log.error("用户登陆-用户名不存在 username:{}", username);
            }
            return null;
        }finally {
            // 清除认证上下文
            AuthenticationContextHolder.clear();
        }

        UserAuthDetail userAuthDetail = (UserAuthDetail) authenticate.getPrincipal();
        return tokenService.createToken(userAuthDetail);
    }
}
